﻿Imports System.Drawing
Imports System.Drawing.Drawing2D
Imports System.Drawing.Imaging
Imports System.Runtime.Serialization.Json

Public Class Helpers

    Public Shared Function validateCall() As Boolean


        Return True
    End Function

    Public Shared Sub ExceptionWrapper(ex As Exception)

        '' aca en base a parametros se podria ver si se dispara el error, se loguea en algun txt.. o lo que sea

        Throw ex

    End Sub

    Public Shared Function getConfig(key As String) As String
        Try
            Return System.Configuration.ConfigurationManager.AppSettings(key)
        Catch ex As Exception
            Throw ex
        End Try

    End Function

    ''' <summary>
    ''' Translate to user language
    ''' </summary>
    ''' <param name="key"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Shared Function translate(key As String) As String
        Dim res As String = key
        Try
            ' TODO: sacar de las preferencias del usuario/company el lenguaje
            If System.Web.HttpContext.GetGlobalResourceObject("lang_en", key) IsNot Nothing Then
                res = System.Web.HttpContext.GetGlobalResourceObject("lang_en", key).ToString
            End If
        Catch ex As Exception
            Throw ex
        End Try

        Return res
    End Function

    ''' <summary>
    ''' Save generic log
    ''' </summary>
    ''' <param name="pMensaje"></param>
    ''' <param name="pFileName"></param>
    ''' <remarks></remarks>
    Public Shared Sub SaveLog(ByVal pMensaje As String, Optional ByVal pFileName As String = "Log.txt")

        Try

            Dim path As String
            path = System.Configuration.ConfigurationManager.AppSettings("logsPath")
            Dim w As IO.StreamWriter = IO.File.AppendText(path & pFileName)

            w.Write(ControlChars.CrLf)
            'w.WriteLine("{0} :  {1}", DateTime.Now.ToString("yyyyMMddHHmmss"), pMensaje)
            w.WriteLine("{0} :  {1}", DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss"), pMensaje)
            w.Flush()
            w.Close()
        Catch ex As Exception

        End Try

    End Sub


    ''' <summary>
    ''' Return app path. Ex: c:\inetpub\wwwroot\MapGeoData\
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Shared Function getAppPath() As String
        Try
            Return System.Web.HttpContext.Current.Server.MapPath("~") & "\"
        Catch ex As Exception
            Throw ex
        End Try

    End Function


    ''' <summary>
    ''' Resize image 
    ''' </summary>
    ''' <param name="sourceImage"></param>
    ''' <param name="size"></param>
    ''' <param name="preserveAspectRatio"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Shared Function ResizeImage(ByVal sourceImage As Image, ByVal size As Size, Optional ByVal preserveAspectRatio As Boolean = True, Optional ByVal type As String = "") As Image
        Dim newWidth As Integer
        Dim newHeight As Integer
        Dim newImage As Image

        Dim originalWidth As Integer = sourceImage.Width
        Dim originalHeight As Integer = sourceImage.Height
        Dim percentWidth As Single = CSng(size.Width) / CSng(originalWidth)
        Dim percentHeight As Single = CSng(size.Height) / CSng(originalHeight)


        If type IsNot Nothing AndAlso (type.ToLower = "crop" Or type.ToLower = "centercrop") Then
            newWidth = size.Width
            newHeight = size.Height

            Dim percent As Single = If(percentHeight < percentWidth, percentWidth, percentHeight)

            'resize to next crop
            Dim resizeWidth As Integer = CInt(originalWidth * percent)
            Dim resizeHeight As Integer = CInt(originalHeight * percent)

            Dim tmpImage As Image = New Bitmap(resizeWidth, resizeHeight)

            Using graphicsHandle As Graphics = Graphics.FromImage(tmpImage)
                graphicsHandle.InterpolationMode = InterpolationMode.HighQualityBicubic
                graphicsHandle.DrawImage(sourceImage, 0, 0, resizeWidth, resizeHeight)
            End Using


            ' crop
            newImage = New Bitmap(newWidth, newHeight)
            Dim CropRect As Rectangle
            If type.ToLower = "crop" Then
                CropRect = New Rectangle(0, 0, newWidth, newHeight)
            Else
                CropRect = New Rectangle((resizeWidth - newWidth) / 2, (resizeHeight - newHeight) / 2, newWidth, newHeight)
            End If
            Using grp = Graphics.FromImage(newImage)
                grp.InterpolationMode = InterpolationMode.HighQualityBicubic
                grp.DrawImage(tmpImage, New Rectangle(0, 0, CropRect.Width, CropRect.Height), CropRect, GraphicsUnit.Pixel)
                tmpImage.Dispose()

            End Using

        ElseIf preserveAspectRatio Then

            Dim percent As Single = If(percentHeight < percentWidth, percentHeight, percentWidth)

            newWidth = CInt(originalWidth * percent)
            newHeight = CInt(originalHeight * percent)

            newImage = New Bitmap(newWidth, newHeight)

            Using graphicsHandle As Graphics = Graphics.FromImage(newImage)
                graphicsHandle.InterpolationMode = InterpolationMode.HighQualityBicubic
                graphicsHandle.DrawImage(sourceImage, 0, 0, newWidth, newHeight)
            End Using

        End If

        Return newImage
    End Function

    Public Shared Function json_encode(obj As Object) As String

        Return Newtonsoft.Json.JsonConvert.SerializeObject(obj)

        ' old method
        'Dim instance As New DataContractJsonSerializer(GetType(T))
        'Dim sr As New System.IO.MemoryStream()
        'instance.WriteObject(sr, obj)
        'Return System.Text.Encoding.ASCII.GetString(sr.GetBuffer())
    End Function

    Public Shared Function json_decode(Of T)(data As String) As Object

        Return Newtonsoft.Json.JsonConvert.DeserializeObject(Of T)(data)

        'old method
        'Dim instance As New DataContractJsonSerializer(GetType(T))
        'Dim sr As New System.IO.MemoryStream()
        'Dim bytes As Byte() = System.Text.Encoding.ASCII.GetBytes(data)
        'sr.Write(bytes, 0, bytes.Length)
        'Dim obj As T = instance.ReadObject(sr)
        'Return obj

    End Function

End Class